<?php
/**
 * @link https://ym2.cleverstone.top
 * @copyright Copyright (c) 2020 Yii Manager Software LLC
 */

namespace extend\weixin\request;

use extend\weixin\BaseRequest;
use extend\weixin\WxConf;
use extend\weixin\WxPay;
use yii\helpers\ArrayHelper;

/**
 * 生成交易单
 * ```php
 * $request = new JsapiTradeCreate([
 *      'description' => '支付调试',
 *      'out_trade_no' => 'DD00005555',
 *      'amount' => [
 *          'total' => 100,
 *      ],
 *      'payer' => [
 *          'openid' => 'oziZ568Va46lQwm8jnrATvlZLAyM',
 *      ],
 * ], '支付调试');
 *
 * $wxClient = \extend\Extend::wxpay()->setRequest($request);
 * $state = $wxClient->execute();
 * if ($state) {
 *      var_export($wxClient->result);
 * } else {
 *      echo $wxClient->error;
 * }
 * ```
 *
 * @auther clevstn
 * @since 2.0
 * @datetime 2023.11.21 17:02
 */
class JsapiTradeCreate extends BaseRequest
{
    private $_serviceName;
    private $_requestOptions;

    /**
     * @param array $requestOptions Request options
     * @param string $serviceName 服务名称
     * @param string $notifyUri 回调URI
     * @example
     * ```php
     * $requestOptions = [
     *     'description' => '租赁押金',
     *     'out_trade_no' => 'DD2302145775252121',
     *     'amount' => [
     *          'total' => '100', //1元
     *      ],
     *     'payer' => [
     *          'openid' => 'oziZ568Va46lQwm8jnrATvlZLAyM',
     *      ],
     * ]
     * ```
     * @link https://pay.weixin.qq.com/docs/merchant/apis/mini-program-payment/mini-prepay.html
     */
    public function __construct(array $requestOptions, $serviceName, $notifyUri)
    {
        $this->_requestOptions = ArrayHelper::merge([
            'appid' => WxConf::APPID,
            'mchid' => WxConf::MERCHANT_ID,
            'notify_url' => WxConf::MERCHANT_NOTIFY_DOMAIN . $notifyUri,
        ], $requestOptions);
        $this->_serviceName = $serviceName;
    }

    /**
     * {@inheritDoc}
     */
    public function getMethodAsync()
    {
        return 'postAsync';
    }

    /**
     * {@inheritDoc}
     */
    public function getServiceName()
    {
        return $this->_serviceName;
    }

    /**
     * {@inheritDoc}
     */
    public function getChain()
    {
        return '/v3/pay/transactions/jsapi';
    }

    /**
     * {@inheritDoc}
     */
    public function getRequestOptions()
    {
        return [
            'json' => $this->_requestOptions,
            'verify' => false,
        ];
    }

    /**
     * {@inheritDoc}
     */
    public function responseCallback($response, WxPay $wxpay)
    {
        return null;
    }
}